<script setup>

import {Plus} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import {computed, getCurrentInstance, onMounted, ref} from "vue";
import http from "@/request/Http.js";
import UserMessage from "@/views/user/profile/UserMessage.vue";
import Password from "@/views/user/profile/Password.vue";
import Delete from "@/views/user/profile/Delete.vue";
import {eventBus} from "@/eventBus.js";

//获取当前实例
const instance = getCurrentInstance()

//组件映射
const componentMap = {
  user: UserMessage,
  password: Password,
  delete: Delete
}
const currentComponent = computed(() => {
  return componentMap[activeIndex.value] || UserMessage
})

//当前对象实体
const userInfo = ref({
  imageUrl: ''
})

//=========菜单========
//激活菜单
const activeIndex = ref('user')
//菜单切换方法
const handleSelect = (index) => {
  activeIndex.value = index
}

//========上传图片======
//上传前
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片格式必须是 JPG/PNG!')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

//上传头像方法
const handlerUpload = async (params) => {
  // 检查文件是否存在
  if (!params.file) {
    ElMessage.error('请选择要上传的文件！')
    return
  }

  // 从参数中提取文件对象
  const file = params.file
  // 检查文件对象是否存在
  if (!file) {
    ElMessage.error('文件对象为空！')
    return
  }

  // 获取上传的图片对象
  const formData = new FormData()
  formData.append('file', file)

  try {
    const response = await http.post('/file/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    console.log('图片上传响应:', response)
    //将头像URL赋值给用户信息
    userInfo.value.imageUrl = response
    ElMessage.success('头像上传成功')

    //将头像URL存进后台
    const updateResponse = await http.post('/user/updateAvatar', {avatar: response})
    // 检查头像更新是否成功
    console.log("头像更新响应:", updateResponse)
    if (updateResponse.code === 200) {
      ElMessage.success('头像更新成功')
      eventBus.emit('avatar-updated', response)
      updateParentUserInfo()
    } else {
      ElMessage.error('头像更新失败: ' + (updateResponse.data?.msg || '未知错误'))
    }

  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请重试')
  }
}

// 更新父组件的用户信息
const updateParentUserInfo = () => {
  // 获取父组件实例并调用其 fetchUserInfo 方法
  const parent = instance?.parent
  console.log('父组件实例:', parent)  // 添加日志以调试
  if (parent && parent.exposed && typeof parent.exposed.fetchUserInfo === 'function') {
    console.log('调用父组件的 fetchUserInfo 方法')
    parent.exposed.fetchUserInfo()
  } else {
    console.log('无法获取父组件的 fetchUserInfo 方法')
  }
}


// 获取用户信息的方法
const fetchUserInfo = async () => {
  try {
    const response = await http.get('/user/getUserInfo')
    if (response.code === 200) {
      const userData = response.data
      // 更新用户信息
      userInfo.value.imageUrl = userData.avatar
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

//上传成功
const handleAvatarSuccess = (response, uploadFile) => {

}

// 初始化时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<template>
  <!-- 布局容器 一行连列-->
  <el-row :gutter="20" :justif="'center'" style="height: 100vh; padding: 1rem">
    <el-col :span="8">
      <!--        左列  用户信息栏-->
      <el-card style="max-width: 480px">
        <template #header>
          <div class="card-header" style="width: 100%; display: flex;
             justify-content: center; align-content: center">
            <span>个人信息</span>
          </div>
        </template>

        <!--          卡片主体内容区域-->
        <!--            第一行 头像-->
        <div class="avatar-container">
          <el-upload
              :before-upload="beforeAvatarUpload"
              :http-request="handlerUpload"
              :on-success="handleAvatarSuccess"
              :show-file-list="false"
              class="avatar-uploader"
          >
            <img v-if="userInfo.imageUrl" :src="userInfo.imageUrl" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
          <div class="avatar-tip">点击上传头像</div>
        </div>
      </el-card>
    </el-col>
    <!--      右列-->
    <el-col :span="16">
      <el-card style="width: 100%">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            @select="handleSelect"
        >
          <el-menu-item index="user">
            <span slot="title">基本信息</span>
          </el-menu-item>
          <el-menu-item index="password">
            <span slot="title">修改密码</span>
          </el-menu-item>
          <el-menu-item index="delete">
            <span slot="title">账号管理</span>
          </el-menu-item>
        </el-menu>
        <!-- 动态组件显示区域 -->
        <div class="content-area">
          <component :is="currentComponent"/>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<style scoped>
.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px 0;
}

.avatar-uploader {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  position: relative;
  border: 1px dashed #d9d9d9;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader .avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.avatar-tip {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}
</style>